<!--
 * @Date: 2023-03-08 21:54:29
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-10 19:48:33
 * @FilePath: \A19\frontend\src\components\Test\Draft.vue
-->
<template>
<ElButton @click="dialogVisible = true" style="margin-left: 50px;" type="success">草稿</ElButton>
<el-dialog
    v-model="dialogVisible"
    title="草稿"
    width="60%"
    custom-class="draft-dia"
  >
  <el-table
    ref="singleTableRef"
    :data="drafts"
    highlight-current-row
    style="width: 100%"
    @current-change="handleCurrentChange"
  >
    <el-table-column type="index" width="50" />
    <el-table-column property="name"   />
  </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">
          选择草稿
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { questions } from "@/shared/types/Question";
import { ref, onMounted, watch, reactive } from 'vue';
import { useClientStore } from '../../pinia/stores/client';
import { tests } from '../../shared/types/tests';
import { storeToRefs } from 'pinia';

const props = defineProps<{ questions:Array<questions>,examOrHomework:'exam' | 'homework' }>();
const store = useClientStore()
// const {currentCourseId} = storeToRefs(store)
// console.log(store.currentCourseId);

const drafts = ref(new Array<tests>)

const dialogVisible = ref(false)
watch(dialogVisible,async (newValue) =>{
  if(newValue){
    const ret = await store.client.callApi('Get/GetCourseTest',{
      course:store.currentCourseId,
      examOrHomework:props.examOrHomework
    }) 
    if(ret.isSucc){
      drafts.value = ret.res.tests.filter(test => test.status === 'saved')
    }
  }
})
const currentTestId = ref<string>()
const handleCurrentChange = (val: tests | undefined)=>{
  currentTestId.value = val?._id
}
let loadingInstance:any
const submit = async ()=>{
  loadingInstance = ElLoading.service({
    target:'.draft-dia',
  })
  if(!currentTestId.value){
    ElMessage.warning('请选择一个草稿')
  }
  else{
    const ret = await store.client.callApi('Get/GetTestQuestions',{
      test:currentTestId.value,
      examOrHomework:props.examOrHomework
    })
    if(ret.isSucc){
      if(ret.res.test.length === 0){
        ElMessage.warning('不存在')
      }
      else{
        props.questions.length = 0
        props.questions.push(...ret.res.test[0].questions as Array<questions>)
        dialogVisible.value = false
        currentTestId.value = ''
      }
    }
  }

  loadingInstance.close()
}
const cancel = () =>{
  dialogVisible.value = false
  currentTestId.value = ''
}
</script>

<style lang="less" scoped>

.tests{
  // display: flex;
  // flex-direction: column;
  .test{
    // height: 30px;
    // line-height: 30px;

    .name{

    }
  }
}
</style>